/**  
 * All rights Reserved, Designed By www.tydic.com
 * @Title:  AccountServiceImpl.java   
 * @Package com.axin.service.impl   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: axin     
 * @date:   2019年4月2日 下午10:13:17   
 * @version V1.0 
 * @Copyright: 2019 www.hao456.top Inc. All rights reserved. 
 */
package com.axin.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.axin.common.entity.ApiToken;
import com.axin.common.entity.DataGridResult;
import com.axin.common.entity.response.Accounts;
import com.axin.common.entity.response.AccountsResponse;
import com.axin.common.entity.response.Balance;
import com.axin.common.entity.response.BalanceBean;
import com.axin.common.entity.response.BalanceResponse;
import com.axin.common.exception.AccountLockException;
import com.axin.common.exception.ApiException;
import com.axin.common.huobi.HttpRequest;
import com.axin.entity.vo.BalanceVO;
import com.axin.service.AccountService;
import com.axin.service.MarketService;
import com.fasterxml.jackson.core.type.TypeReference;


/**   
 * @Description: 账户相关 
 * @ClassName:  AccountServiceImpl
 * @author:  Axin 
 * @date:   2019年4月2日 下午10:13:17   
 * @Copyright: 2019 www.hao456.top Inc. All rights reserved. 
 */
@Service
public class AccountServiceImpl implements AccountService{

	
	@Value("${API_ACCOUNT_ACCOUNTS}")
	private String API_ACCOUNT_ACCOUNTS;
	
	@Value("${API_ACCOUNT_ACCOUNTS_BALANCE}")
	private String API_ACCOUNT_ACCOUNTS_BALANCE;
	
	@Autowired
	private HttpRequest httpRequest;
	@Autowired
	private MarketService marketService;
	

	@Override
	public List<Accounts> getAccounts(ApiToken token) throws ApiException,Exception {
		AccountsResponse<List<Accounts>> res = httpRequest.get(token, API_ACCOUNT_ACCOUNTS, null, new TypeReference<AccountsResponse<List<Accounts>>>(){});
		List<Accounts> list = res.checkAndReturn();
		return list;
	}
	
	
	


	/* (non-Javadoc)
	 * @see com.axin.service.AccountService#getAccountsByType(com.axin.common.entity.ApiToken, java.lang.String)
	 */
	@Override
	public Integer getAccountsByType(ApiToken token, String type) throws ApiException, Exception {
		  List<Accounts> accounts = getAccounts(token);
		  if(CollectionUtils.isEmpty(accounts)){
				throw new RuntimeException("账户查询结果为空。");
			}
		  	Accounts result = null;
			for (Accounts account : accounts) {
				String itemType = account.getType();
				if(type.equals(itemType)){
					result = account;
					break;
				}
			}
			if(result != null){
				String state = result.getState();
				if("lock".equals(state)){
					throw new AccountLockException(type +" 账户现处于锁定状态");
				}
			}
			if(result == null){
				return null;
			}
			
			return result.getId();
	}





	/* (non-Javadoc)
	 * @see com.axin.service.AccountService#getBalance(com.axin.common.entity.ApiToken, java.lang.Integer)
	 */
	@Override
	public Balance<List<BalanceBean>> getBalance(ApiToken token, Integer id) throws ApiException, Exception {
		if(id == null){
			throw new  NullPointerException("账户id不能为空");
		}
		String tempUrl = new String(API_ACCOUNT_ACCOUNTS_BALANCE); 
		String newUrl = tempUrl.replace("{account-id}", id+"");
		BalanceResponse<Balance<List<BalanceBean>>> res = httpRequest.get(token, newUrl, null, new TypeReference<BalanceResponse<Balance<List<BalanceBean>>>>(){});
		Balance<List<BalanceBean>> balance = res.checkAndReturn();
		return balance;
	}


	



	/* (non-Javadoc)
	 * @see com.axin.service.AccountService#getBalanceList(com.axin.common.entity.ApiToken)
	 */
	@Override
	public DataGridResult getBalanceList(ApiToken token,Integer id) throws ApiException, Exception {
		if(id == null){
			id = getAccountsByType(token, AccountService.TYPE_SPOT);
		}
		Balance<List<BalanceBean>> balance = getBalance(token, id);
		List<BalanceBean> list = balance.getList();
		Map<String,BalanceVO> filter = new HashMap<>();
//		List<BalanceVO> beforeList = new ArrayList<>();
		List<BalanceVO> nList = new ArrayList<>();
//		BigDecimal totalBtc = new BigDecimal(0);
		for (BalanceBean item : list) {
			String currency = item.getCurrency();
			String type = item.getType();
			String itemBalance = item.getBalance();
//			if(AccountService.BALANCE_TYPE_TRADE.equals(type)){
//				BigDecimal itemBalanceBig = new BigDecimal(itemBalance);
//				if(itemBalanceBig.doubleValue()!=0){
//					Merged merged = marketService.getDetailMerged(token, currency+"btc");
//					BigDecimal symbolPrice = new BigDecimal(merged.getClose());
//					BigDecimal money = itemBalanceBig.multiply(symbolPrice).setScale(8, BigDecimal.ROUND_HALF_UP);
//					totalBtc = totalBtc.add(money).setScale(8, BigDecimal.ROUND_HALF_UP);
//				}
//			}
			
			
			if(filter.containsKey(currency)){
				BalanceVO vo = filter.get(currency);
				if(AccountService.BALANCE_TYPE_TRADE.equals(type)){
					vo.setTradeBalance(itemBalance);
				}else if(AccountService.BALANCE_TYPE_FROZEN.equals(type)){
					vo.setFrozenBalance(itemBalance);
				}
			}else{
				BalanceVO vo = new BalanceVO();
				vo.setCurrency(currency);
				if(AccountService.BALANCE_TYPE_TRADE.equals(type)){
					vo.setTradeBalance(itemBalance);
				}else if(AccountService.BALANCE_TYPE_FROZEN.equals(type)){
					vo.setFrozenBalance(itemBalance);
				}
				nList.add(vo);
//				if(currency.equals("usdt") || currency.equals("husd")
//						|| currency.equals("btc")
//						|| currency.equals("eth")
//						|| currency.equals("eos")
//						|| currency.equals("ht")){
//					beforeList.add(vo);
//				}else{
//				}
				filter.put(currency, vo);
				
			}
		}
		//按余额大小排序
		Collections.sort(nList, new OrderByBalance());
		//beforeList.addAll(nList);
		Map<String,Object> map = new HashMap<>();
		map.put("type", balance.getType());
		map.put("state", balance.getState());
//		map.put("btcTotal", totalBtc.setScale(8, BigDecimal.ROUND_HALF_UP).toPlainString());
		return new DataGridResult(nList.size(),nList,map);
	}





	/* (non-Javadoc)
	 * @see com.axin.service.AccountService#getBalanceByAccountId(com.axin.common.entity.ApiToken, java.lang.Integer, java.lang.String)
	 */
	@Override
	public BalanceBean getBalanceByAccountId(ApiToken token, Integer id, String type,String currency) throws ApiException,  AccountLockException,Exception {
		Balance<List<BalanceBean>> balance = getBalance(token, id);
		
		String state = balance.getState();
		if("lock".equals(state)){
			throw new AccountLockException(balance.getType() +" 账户现处于锁定状态");
		}
		List<BalanceBean> list = balance.getList();
		for (BalanceBean item : list) {
			String curType = item.getType();
			String curCurrency = item.getCurrency();
			if(type.equals(curType) && currency.equals(curCurrency)){
				return item;
			}
		}
		return null;
	}
	
	
	
	
	
	

	
	
	
}

class OrderByBalance implements Comparator <BalanceVO>{

	@Override
	public int compare(BalanceVO o1, BalanceVO o2) {

		 String a1 = o1.getTradeBalance();
		 String a2 = o2.getTradeBalance();
		 
		 if(a1.compareTo(a2) < 0){
		    return 1;
		 }else if(a1.compareTo(a2) > 0){
		    return -1;
		 }
		return 0;
	}
	
	
}
